package business;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import util.OjdbcUtil;

public class Tools {

	private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
	private static Map mapPhonPut = new HashMap();
	public static String GetMessageCode(String remsg) {
		// TODO Auto-generated method stub
		HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod(Url);
		client.getParams().setContentCharset("GBK");
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");
		int mobile_code = (int)((Math.random()*9+1)*100000);
		String content = new String("您本次流动人口申报的验证码是：" + mobile_code + "。请勿告知他人");
		NameValuePair[] data = {
			    new NameValuePair("account", "C23077428"), //�鿴�û����ǵ�¼�û�����->��֤�����->��Ʒ����->APIID
			    new NameValuePair("password", "9817e39488d3cbc9ee75660998432b58"),  //�鿴�������¼�û�����->��֤�����->��Ʒ����->APIKEY
			    //new NameValuePair("password", util.StringUtil.MD5Encode("����")),
			    new NameValuePair("mobile", remsg), 
			    new NameValuePair("content", content),
		};
		method.setRequestBody(data);
		try {
			client.executeMethod(method);		
			String SubmitResult =method.getResponseBodyAsString();
			//System.out.println(SubmitResult);
			Document doc = DocumentHelper.parseText(SubmitResult);
			Element root = doc.getRootElement();
			String code = root.elementText("code");
			String msg = root.elementText("msg");
			String smsid = root.elementText("smsid");
			System.out.println(code);
			System.out.println(msg);
			System.out.println(smsid);
			mapPhonPut.put("remsg", mobile_code);
			//入库操作先屏蔽
			OjdbcUtil ojdbc = new OjdbcUtil();
			Connection coon =ojdbc.getConn();
			String sql = "insert into t_phone (phoneNumber,yanzhengma) values('"+remsg+"','"+mobile_code+"')";
			System.out.println(sql);
			String flag = "";
			PreparedStatement sta = coon.prepareStatement(sql);
			int rs = sta.executeUpdate(sql);
			 if("2".equals(code)){
				System.out.println("�����ύ�ɹ�");
			}
		}
		catch(Exception e){
			return e.getMessage();
		}
		return remsg;
	}

	public static String GetOCR(String remsg) throws IOException {
		// TODO Auto-generated method stub
		String urlstr = "http://101.207.250.6:91/HotelAndroid/getToken.do?id=8915573f0c536dfb6239787fc53cb9da4957532a&secret=f7c3bc1d808e04732adf679965ccc34ca7ae3441\r\n" + 
				"";
		try{
			URL url = new URL(urlstr);
			URLConnection con = url.openConnection();
			con.setRequestProperty("Cache-Control", "no-cache");
			con.setRequestProperty("Content-Type", "application/json");
			con.setDoOutput(true); // 默认是无法向服务器写数据的
			con.setDoInput(true);
			OutputStreamWriter out = new OutputStreamWriter(con
					.getOutputStream(),"UTF-8"); 
			JSONObject json = new JSONObject();		
			out.flush();
			out.close();
			InputStream inputStream = con.getInputStream();
			byte[] buffer = new byte[1024];    
			int len = 0;    
			ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
			while((len = inputStream.read(buffer)) != -1) { 
				bos.write(buffer, 0, len);    
			}    
			bos.close(); 
			byte[] getData = bos.toByteArray();
			String data = new String( getData ,"utf-8");
			JSONObject jsonm = JSONObject.parseObject(data);
			System.out.println(data);
			
			String token = jsonm.getString("body");
			String ImgBase64 = remsg.substring(remsg.indexOf(",")+1);
			String IDType = "11";
			String checkin_type  = "0";
			
			
			String urlstr1 = "http://101.207.250.6:91/HotelAndroid/OcrResoluIdCard.do?token="+token;	
			URL url1 = new URL(urlstr1);
			URLConnection con1 = url1.openConnection();
			con1.setDoOutput(true);
			con1.setDoOutput(true);
			con1.setRequestProperty("Cache-Control", "no-cache");
			con1.setRequestProperty("Content-Type", "application/json");
			OutputStreamWriter out1 = new OutputStreamWriter(con1
					.getOutputStream(),"UTF-8"); 
			String base64=ImgBase64;
			JSONObject json1 = new JSONObject();
			String str="";
			str+="ImgBase64="+base64;
			json1.put("ImgBase64", base64);
			
			
			System.out.println("==="+str.toString() );
			out1.write(json1.toString());
			out1.flush();
			out1.close();
			
			InputStream inputStream1 = con1.getInputStream();
			byte[] buffer1 = new byte[1024];    
			int len1 = 0;    
			ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); 
			while((len1 = inputStream1.read(buffer1)) != -1) { 
				bos1.write(buffer1, 0, len1);    
			}    
			bos1.close(); 
			byte[] getData1 = bos1.toByteArray();
			String data1 = new String( getData1 ,"utf-8");
			System.out.println(data1);
	
			JSONObject json2 =JSONObject.parseObject(data1);
			JSONObject obj = (JSONObject) json2.get("obj");
			String birth = obj.getString("birth");
			String sex = obj.getString("sex");
			String cardno = obj.getString("CardNO");
			String name = obj.getString("name");
			JSONObject list =new JSONObject();
			list.put("birth", birth);
			list.put("sex", sex);
			list.put("cardno", cardno);
			list.put("name", name);
			
			return JSON.toJSONString(list);
		}catch(Exception e){
			return "";
		}
		
	}

	public static String Login(String phone, String yanzhengma) {
		// TODO Auto-generated method stub
		OjdbcUtil ojdbc = new OjdbcUtil();
		Connection coon =ojdbc.getConn();
		String sql = "select count(*) from t_phone where phoneNumber='"+phone+"' and yanzhengma = '"+yanzhengma+"'";
		System.out.println(sql);
		try {
			PreparedStatement sta = coon.prepareStatement(sql);
			ResultSet rs = sta.executeQuery();
			while(rs.next()){
				return "Y";
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			return "N";
		}
		return "N";
	}

	public static String GetJDXServlet(String remsg) {
		// TODO Auto-generated method stub
		if(remsg==null||remsg.equals("null")||remsg.equals("")){
			try {
			OjdbcUtil ojdbc = new OjdbcUtil();
			Connection coon =ojdbc.getConn();
			String sql = "select distinct xzqhdm_qx,xzqhmc_qx from T_DZXXB where xzqhdm_ds='510100'";
			System.out.println(sql);
			String flag = "";
				Map map = new HashMap();
				PreparedStatement sta = coon.prepareStatement(sql);
				ResultSet rs = sta.executeQuery();
				while(rs.next()){
					map.put(rs.getString(1), rs.getString(2));
				}
				String response =JSON.toJSONString(map);
				return response;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return e.getMessage();
			}
		}else{
			try {
				OjdbcUtil ojdbc = new OjdbcUtil();
				Connection coon =ojdbc.getConn();
				String sql = "select distinct jlxdm,jlxmc from T_DZXXB where xzqhdm_qx='"+remsg+"' and jlxdm is not null";
				System.out.println(sql);
				String flag = "";
					Map map = new HashMap();
					PreparedStatement sta = coon.prepareStatement(sql);
					ResultSet rs = sta.executeQuery();
					while(rs.next()){
						map.put(rs.getString(1), rs.getString(2));
					}
					String response =JSON.toJSONString(map);
					return response;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return e.getMessage();
				}
			
		}
		
	}

	public static String InsertMan(String idNumber, String name, String birth, String sex) {
		// TODO Auto-generated method stub
		/*try {
			OjdbcUtil ojdbc = new OjdbcUtil();
			Connection coon =ojdbc.getConn();
			String sql = "";
			System.out.println(sql);
			String flag = "";
				Map map = new HashMap();
				PreparedStatement sta = coon.prepareStatement(sql);
				ResultSet rs = sta.executeQuery();
				while(rs.next()){
					map.put(rs.getString(1), rs.getString(2));
				}
				String response =JSON.toJSONString(map);
				return response;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return e.getMessage();
			}*/
		return "Y"+"*"+"id";
	}

	public static String MessageInsert(String fangdong, String fangdongdianhua, String fangdongshenfenzheng,
			String jiedaoid, String menpai, String dong, String dongfu, String danyuan, String danyuanfu, String ceng,
			String shi, String phone) {
		// TODO Auto-generated method stub
		//街道id对应排除锁
		/*try {
			OjdbcUtil ojdbc = new OjdbcUtil();
			Connection coon =ojdbc.getConn();
			String sql = "";
			System.out.println(sql);
			String flag = "";
				Map map = new HashMap();
				PreparedStatement sta = coon.prepareStatement(sql);
				ResultSet rs = sta.executeQuery();
				while(rs.next()){
					map.put(rs.getString(1), rs.getString(2));
				}
				String response =JSON.toJSONString(map);
				return response;
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return e.getMessage();
			}*/
		HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod(Url);
		client.getParams().setContentCharset("GBK");
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");
		int mobile_code = (int)((Math.random()*9+1)*100000);
		String content = new String("您的申报已成功，申报码：" + mobile_code + "，请保持通讯畅通。经审核通过，居住期满六个月后，可向您居住地派出所申领居住证，可享受居住地相关权益。");
		NameValuePair[] data = {
			    new NameValuePair("account", "C23077428"), //�鿴�û����ǵ�¼�û�����->��֤�����->��Ʒ����->APIID
			    new NameValuePair("password", "9817e39488d3cbc9ee75660998432b58"),  //�鿴�������¼�û�����->��֤�����->��Ʒ����->APIKEY
			    //new NameValuePair("password", util.StringUtil.MD5Encode("����")),
			    new NameValuePair("mobile", phone), 
			    new NameValuePair("content", content),
		};
		method.setRequestBody(data);
		try {
			client.executeMethod(method);		
			String SubmitResult =method.getResponseBodyAsString();
			//System.out.println(SubmitResult);
			Document doc = DocumentHelper.parseText(SubmitResult);
			Element root = doc.getRootElement();
			String code = root.elementText("code");
			String msg = root.elementText("msg");
			String smsid = root.elementText("smsid");
			System.out.println(code);
			System.out.println(msg);
			System.out.println(smsid);
			mapPhonPut.put("remsg", mobile_code);
			//入库操作先屏蔽
			/*OjdbcUtil ojdbc = new OjdbcUtil();
			Connection coon =ojdbc.getConn();
			String sql = "insert into t_phone where (phoneNumber,yanzhengma) values('"+remsg+"','"+mobile_code+"')";
			System.out.println(sql);
			String flag = "";
			PreparedStatement sta = coon.prepareStatement(sql);
			int rs = sta.executeUpdate(sql);*/
			 if("2".equals(code)){
				System.out.println("�����ύ�ɹ�");
			}
		}
			catch(Exception e){
			return "N";
		}
		return "Y";
		
		
	}

}
